package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradePaymentWindowBean;
import com.atguigu.func.MyWindowFunction;
import com.atguigu.uitl.ClickHouseUtil;
import com.atguigu.uitl.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/17 20:38
 */
public class Dws07_TradePaymentSucWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HAOOP_USER_NAME","atguigu");
        //todo 2 从kafka（dwd_cart_info）读数据
        String topic="dwd_trade_pay_detail_suc";
        String groupID="trade_payment_suc_0926";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupID));
        //todo 3 将数据转为JSONObj对象，并提取waterMark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = kafkaDS.map(JSONObject::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("callback_time");
                            }
                        })));

        //todo 4 按照uid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWMDS.keyBy(value -> value.getString("user_id"));
        
        //todo 5 转为javaBean对象
        SingleOutputStreamOperator<TradePaymentWindowBean> tradePaymentWindowBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, TradePaymentWindowBean>() {
            private ValueState<String> lastPayDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastPayDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last_pay_dt", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentWindowBean> out) throws Exception {
                String lastDt = lastPayDtState.value();
                String curtDt = value.getString("callback_time").split(" ")[0];
                Long uniqueUv = 0L;
                Long newUv = 0L;
                if (lastDt == null) {
                    uniqueUv = 1L;
                    newUv = 1L;
                    lastPayDtState.update(curtDt);
                } else if (!lastDt.equals(curtDt)) {
                    uniqueUv = 1L;
                    lastPayDtState.update(curtDt);
                }

                if (uniqueUv == 1L) {
                    out.collect(new TradePaymentWindowBean("",
                            "",
                            uniqueUv,
                            newUv,
                            null));
                }
            }
        });

        //todo 6 开窗聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> resultDS = tradePaymentWindowBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                        value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                        value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                        return value1;
                    }
                }, new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean next = values.iterator().next();
                        out.collect(MyWindowFunction.getJavaBeanField(next, window));
                    }
                });

        //todo 7 写出数据到clickHouse
        resultDS.print("resultDS>>>>>>>>>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_payment_suc_window values(?,?,?,?,?)"));
        //todo 8 启动程序
        env.execute("Dws07_TradePaymentSucWindow");
    }
}
